package com.woniuxy.educationplatform.controller;

import com.woniuxy.educationplatform.bean.AdminBean;
import com.woniuxy.educationplatform.service.IAdminService;
import com.woniuxy.educationplatform.util.ExcelUtil;
import com.woniuxy.educationplatform.util.ResultUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * 解析Excel文件
 * @author unreleased
 * @date 2020/12/15 19:02
 */
@RestController
@RequestMapping("/files")
public class FileController {
    @Resource
    private IAdminService adminServiceImpl;

    @PostMapping("/parsingExcel")
    public ResultUtil upload(@RequestParam("file") MultipartFile file) throws Exception {
        ResultUtil resultUtil = new ResultUtil();
        //首先判断名字是够xlsx结尾的或者xls结尾的
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
             return resultUtil.setCode(ResultUtil.ERROR);
        }
        if(!(originalFilename.endsWith(".xls")||originalFilename.endsWith(".xlsx"))){
            return resultUtil.setCode(ResultUtil.ERROR).setMessage("请传入.xls或.xlsx结尾的文件");
        }
        List<AdminBean> objects = (List<AdminBean>) ExcelUtil.importExcel(file.getInputStream(), AdminBean.class);
        System.out.println(objects.size());
        for (AdminBean adminBean : objects) {
            adminServiceImpl.addAdmin(adminBean);
        }
         return new ResultUtil().setCode(ResultUtil.SUCCESS).setMessage("导入成功");
    }
}
